<template>
  <div class="task-list">
    <el-card>
      <template #header>
        <div class="card-header">
          <h3>定时任务列表</h3>
          <el-button type="primary" @click="handleAdd">+ 新增定时任务</el-button>
        </div>
      </template>

      <el-table :data="taskList" border v-loading="loading">
        <el-table-column prop="id" label="ID编号" width="80" align="center" />
        <el-table-column label="类型" width="90" align="center">
          <template #default="scope">
            <span v-if="scope.row.types === 1" class="red">系统任务</span>
            <span v-else-if="scope.row.types === 2" class="blue">普通任务</span>
            <span v-else class="green">自定义任务</span>
          </template>
        </el-table-column>
        <el-table-column prop="title" label="任务名称" width="200" />
        <el-table-column prop="link" label="任务链接" width="300" />
        <el-table-column prop="desc" label="任务描述" />
        <el-table-column label="操作" width="100" align="center">
          <template #default="scope">
            <el-button size="small" @click="handleView(scope.row)">查看</el-button>
            <el-dropdown>
              <el-button size="small">
                更多
                <el-icon><ArrowDown /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="handleEdit(scope.row)">编辑</el-dropdown-item>
                  <el-dropdown-item @click="handleDelete(scope.row)">删除</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 任务编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="600px"
      @close="handleDialogClose"
    >
      <el-alert
        title="注意：定时任务目前只是记录，具体需要技术人员自行在系统服务器添加定时任务计划。"
        type="warning"
        show-icon
        :closable="false"
        class="mb-4"
      />

      <el-form :model="taskForm" :rules="taskRules" ref="taskFormRef" label-width="120px">
        <el-form-item label="任务名称" prop="title">
          <el-input v-model="taskForm.title" placeholder="请输入任务名称" />
        </el-form-item>

        <el-form-item label="任务访问链接" prop="link">
          <el-input v-model="taskForm.link" placeholder="请输入任务访问链接" />
        </el-form-item>

        <el-form-item label="任务描述">
          <el-input
            v-model="taskForm.desc"
            type="textarea"
            :rows="3"
            placeholder="请输入任务描述，不能超过200个字"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitTask">立即提交</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import {
    getTaskList as getTaskListApi,
    saveTask as saveTaskApi,
    deleteTask as deleteTaskApi,
  } from '../../api/home/task'
  import { ArrowDown } from '@element-plus/icons-vue'

  // 数据相关
  const taskList = ref<any[]>([])
  const loading = ref(false)

  // 对话框相关
  const dialogVisible = ref(false)
  const dialogTitle = ref('')
  const isEdit = ref(false)

  // 表单数据
  const taskForm = reactive({
    id: 0,
    types: 3,
    title: '',
    link: '',
    desc: '',
  })

  // 表单验证规则
  const taskRules = {
    title: [{ required: true, message: '请输入任务名称', trigger: 'blur' }],
  }

  // 表单引用
  const taskFormRef = ref()

  // 获取任务列表
  const getTaskList = async () => {
    try {
      loading.value = true
      const response: any = await getTaskListApi()

      if (response.code === 0) {
        // 确保数据格式正确
        if (Array.isArray(response.data)) {
          taskList.value = response.data
        } else {
          console.warn('Task list data format is incorrect:', response.data)
          taskList.value = []
        }
      } else {
        ElMessage.error(response.msg || '获取任务列表失败')
        taskList.value = []
      }
    } catch (error) {
      console.error('Failed to fetch task list:', error)
      ElMessage.error('获取任务列表失败: ' + ((error as any).message || '未知错误'))
      taskList.value = []
    } finally {
      loading.value = false
    }
  }

  // 处理添加
  const handleAdd = () => {
    isEdit.value = false
    dialogTitle.value = '添加任务'
    taskForm.id = 0
    taskForm.types = 3
    taskForm.title = ''
    taskForm.link = ''
    taskForm.desc = ''
    dialogVisible.value = true
  }

  // 处理编辑
  const handleEdit = (row: any) => {
    isEdit.value = true
    dialogTitle.value = '编辑任务'
    taskForm.id = row.id
    taskForm.types = row.types
    taskForm.title = row.title
    taskForm.link = row.link
    taskForm.desc = row.desc || ''
    dialogVisible.value = true
  }

  // 查看任务详情
  const handleView = (row: any) => {
    // 使用弹窗展示任务详情
    ElMessageBox.alert(
      `
    <p><strong>ID编号:</strong> ${row.id}</p>
    <p><strong>类型:</strong> ${row.types === 1 ? '系统任务' : row.types === 2 ? '普通任务' : '自定义任务'}</p>
    <p><strong>任务名称:</strong> ${row.title}</p>
    <p><strong>任务链接:</strong> ${row.link || '无'}</p>
    <p><strong>任务描述:</strong> ${row.desc || '无'}</p>
  `,
      '查看任务',
      {
        dangerouslyUseHTMLString: true,
        confirmButtonText: '确定',
      }
    )
  }

  // 删除任务
  const handleDelete = async (row: any) => {
    ElMessageBox.confirm(`确认删除任务【${row.title}】吗？`, '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(async () => {
        try {
          const response: any = await deleteTaskApi({ id: row.id })

          if (response.code === 0) {
            ElMessage.success('删除成功')
            await getTaskList()
          } else {
            ElMessage.error(response.msg || '删除失败')
          }
        } catch (error) {
          ElMessage.error('删除失败')
        }
      })
      .catch(() => {
        // 用户取消删除
      })
  }

  // 提交任务
  const submitTask = async () => {
    if (!taskFormRef.value) return

    try {
      await taskFormRef.value.validate()

      const params = {
        id: taskForm.id,
        types: taskForm.types,
        title: taskForm.title,
        link: taskForm.link,
        desc: taskForm.desc,
      }

      const response: any = await saveTaskApi(params)

      if (response.code === 0) {
        ElMessage.success(isEdit.value ? '编辑成功' : '添加成功')
        dialogVisible.value = false
        await getTaskList()
      } else {
        ElMessage.error(response.msg || (isEdit.value ? '编辑失败' : '添加失败'))
      }
    } catch (error) {
      ElMessage.error(isEdit.value ? '编辑失败' : '添加失败')
    }
  }

  // 关闭对话框
  const handleDialogClose = () => {
    taskFormRef.value?.resetFields()
  }

  // 组件挂载时获取数据
  onMounted(() => {
    getTaskList()
  })
</script>

<style scoped>
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .red {
    color: #f56c6c;
  }

  .blue {
    color: #409eff;
  }

  .green {
    color: #67c23a;
  }

  .mb-4 {
    margin-bottom: 1rem;
  }
</style>
